/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.framework.database;

import java.math.BigDecimal;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Predicate represents a logic condition to be used in a sql statement
 * as filter to select a result
 * set.
 */
public class Predicate {
    protected static Log log = LogFactory.getLog(Predicate.class.getName());
    Object mField;
    Object mValue;
    Predicate superPredicate;
    String mOperator;
    String query;
    int bindOrder = -1;
    int orderCounter = 1;
     
    
    public Predicate(String query) {
        this.query = query;
    }

    public Predicate(Object pField, Object pValue, String pOperator) {
        mField = pField;
        mValue = pValue;

        if (mField instanceof Predicate) {
            ((Predicate)mField).superPredicate = this;
        }

        if (mValue instanceof Predicate) {
            ((Predicate)mValue).superPredicate = this;
        }

        mOperator = pOperator;
    }

    public Predicate getRootPredicate() {
        return (superPredicate == null) ? this : 
               superPredicate.getRootPredicate();
    }

    public Predicate AND(Predicate pred) {
        if(pred==null)
            return this;
        
        return new Predicate(this, pred, "AND");
    }

    public Predicate OR(Predicate pred) {
        if(pred==null)
            return this;
        return new Predicate(this, pred, "OR");
    }

    public void bindStatement(PreparedStatement statement) throws SQLException {
        if (mField instanceof Predicate) {
            ((Predicate)mField).bindStatement(statement);
        }

        if (mValue instanceof Predicate) {
            ((Predicate)mValue).bindStatement(statement);
        } else {
            bindValue(statement);
        }
    }

    public String toString() {
        //reset if it is a root predicate
        if (superPredicate == null) {
            reset();
        }

        if (query != null) {
            return query;
        }

        String queryString;

        if (mField instanceof Predicate) {
            queryString = "(" + mField + ") " + mOperator;
        } else {
            queryString = mField + " " + mOperator;
        }

        if (mValue instanceof Predicate) {
            ((Predicate)mValue).bindOrder = bindOrder;
            queryString = queryString + " (" + mValue + ")";
        } else {
            if (mValue != null) {
                String sValue = mValue.toString();

                if (sValue.indexOf("'") != -1) {
                    sValue = sValue.replaceAll("'", "''");
                }

                int i = getRootPredicate().orderCounter++;
                this.bindOrder = i;
                queryString = queryString + " ?";
            } else {
                queryString = queryString + " null";
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Query " + queryString);
        }

        return queryString;
    }

    private void bindValue(PreparedStatement statement) throws SQLException {
        if (bindOrder == -1) {
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Query Binding " + this.mField + " " + mValue + " " + 
                      bindOrder);
        }

        if (mValue == null) {
            statement.setObject(bindOrder, null);
        }

        if (mValue instanceof Calendar) {
            statement.setTimestamp(bindOrder, 
                                   new Timestamp(((Calendar)mValue).getTime().getTime()));
        } else if (mValue instanceof Date) {
            statement.setTimestamp(bindOrder, 
                                   new Timestamp(((Date)mValue).getTime()));
        } else if (mValue instanceof String) {
            statement.setString(bindOrder, "" + mValue);
        } else if (mValue instanceof Number) {
            statement.setBigDecimal(bindOrder, new BigDecimal("" + mValue));
        } else {
            statement.setString(bindOrder, "" + mValue);
        }
    }

    private void reset() {
        bindOrder = -1;
        orderCounter = 1;

        if (mField instanceof Predicate) {
            ((Predicate)mField).reset();
        }

        if (mValue instanceof Predicate) {
            ((Predicate)mValue).reset();
        }
    }
}
